<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="1000">
    <div class="home">
      <div class="left">
        <el-tree default-expand-all :data="treeData" ref="tree" :props="defaultProps" node-key="id"
          @node-click="nodeclick" :highlight-current="highLight" :expand-on-click-node="false">
        </el-tree>
      </div>
      <div class="right">
        <div class="fr">
          <el-form :inline="true" :model="formInline" class="">
            <el-form-item label="关键词" prop="keyword">
              <el-input v-model="formInline.keyword" clearable placeholder="请输入" size="small"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
              <el-button type="primary" plain @click="handleReset" size="small">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- <div class="btn">
        <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      </div> -->
        <el-table v-loading="loading" :data="tableData" ref="tableRef" @selection-change="selectionChange">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="序号" type="index" width="50" :index="indexMethod">
          </el-table-column>
          <el-table-column prop="aircraftType" label="机型"> </el-table-column>
          <el-table-column prop="typeName" label="类型名称"> </el-table-column>
          <el-table-column prop="subTypeName" label="子类型名称" />
          <el-table-column prop="rounds" label="轮次" />
          <el-table-column prop="count" label="计数"> </el-table-column>
        </el-table>

        <el-pagination class="p20 fr" v-if="total > 0" :background="true" :current-page.sync="queryParams.pageNum"
          :page-size.sync="queryParams.pageSize" :layout="'total, sizes, prev, pager, next, jumper'"
          :page-sizes="[10, 30, 50, 100]" :total="total" @size-change="handleSizeChange"
          @current-change="handlepageNumChange" />
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="handleClose">取 消</el-button>
          <el-button size="mini" type="primary" @click="handleConfirm">确 定</el-button>
        </span>

      </div>
    </div>
  </el-dialog>
</template>
<script>
  import { v4 as uuid } from 'uuid';
  import tinymce from "tinymce/tinymce";
  import { getLoadCaseStatisticList, getAllTreeNode } from "@/api/loadCaseStatistics";
  import { saveVeriableValue } from '@/api/computingConfig.js';
  export default {
    name: "ProvisionRepalceDialog",
    data() {
      return {
        title: '选择工况',
        dialogVisible: false,
        formInline: {
          keyword: "",
          classifyId: null
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        loading: false,
        total: 0,
        tableData: [],
        selectionListAll: [],
        isPageChange: false,
        selectionList: [],
        selectionListAll: [],
        idKey: "id",
        treeData: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        currentNode: null,
        highLight: false
      };
    },
    mounted() {
      this.handleSearch();
      this.getTree();
    },
    methods: {
      nodeclick(data, node, prop) {
        this.formInline.classifyId = data?.id;
        this.currentNode = data;
        this.highLight = true;
        this.onSearch();
      },
      processData(data) {
        const labelData = data.map((el) => {
          if (el.children) {
            el = { ...el, label: el.name }
            el.children = this.processData(el.children);
          } else {
            el = { ...el, label: el.name }
          }
          return el;
        })
        return labelData;
      },
      getTree() {
        getAllTreeNode().then(async (res) => {
          if (res) {
            const resultData = res?.data || [];
            console.log(resultData)
            // console.log(resultData.length)
            if (resultData.length > 0) {
              this.treeData = await this.processData(resultData);
              console.log(this.treeData)
            }
          }
        })
      },
      show() {
        this.dialogVisible = true;
      },
      handleClose() {
        this.dialogVisible = false;
      },
      // 合并单元格
      mergeTableCells(table, columnIndex) {
        var rows = table.rows;
        let previousValue = null;
        let rowspan = 1;
        console.log("总行数")
        console.log(rows.length)
        for(let i=1;i<rows.length;i++){
          const currentCell = rows[i].cells[columnIndex];
          if(currentCell){
            const currentValue = currentCell.innerText;
            if(currentValue == previousValue){
              rowspan++;
              rows[i-rowspan+1].cells[columnIndex].rowSpan = rowspan
              rows[i].cells[columnIndex].innerText="";
              rows[i].cells[columnIndex]?.remove();
            }else{
              previousValue = currentValue;
              rowspan=1;
            }
          }
        }
        this.$forceUpdate();
      },
      handleConfirm() {
        if (!this.selectionListAll.length) {
          return this.$message.warning('请选择数据！')
        }
        this.selectionListAll.sort((a, b) => { return a.typeName.localeCompare(b.typeName, 'zh-Hans-CN') });
        this.$store.commit('xmleditor/SET_PROVISION_SELECTIONS', this.selectionListAll)
        const tableTitles = ['工况类型', '子类型', '数量']
        const tableAttrs = ['typeName', 'subTypeName', 'count']
        let sum = 0
        const tableDatas = this.selectionListAll.map((item, index) => {
          item.index = index + 1
          sum += item.count
          return item
        })
        const obj = {
          index: tableDatas.length + 1,
          typeName: '合计',
          subTypeName: '-',
          count: sum
        }
        tableDatas.push(obj)
        const tableId = this.$store.state.xmleditor.variableTableDataId;
        const doc = tinymce.activeEditor.getDoc();
        if (tableId?.dataId) {
          const nodes = doc.querySelector(`[data-id="${tableId?.dataId}"]`)
          const tableChildren = nodes.childNodes;
          tableChildren.forEach(el => {
            if (el.nodeName == 'CAPTION') {
              this.caption = el.innerHTML;
            }
            // 表头设置
            if (el.nodeName == 'THEAD') {
              let tr = '';
              if (tableTitles.length > 0) {
                tableTitles.forEach(title => {
                  let th = '';
                  th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${title}​</p>
	                    </th>`
                  tr += th;
                })
                tr = `<tr data-id="${uuid()}">${tr}</tr>`
              }
              el.innerHTML = tr
            }
            // 数据设置
            if (el.nodeName == 'TBODY') {
              let tbody = '';
              if (tableDatas.length > 0) {
                tableDatas.forEach((dataItem, index) => {
                  let tr = '';
                  tableAttrs.forEach(tdData => {
                    let td = '';
                    td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${dataItem[tdData]}​</p>
	                    </td>`
                    tr += td;
                  })
                  tbody += `<tr data-id="${uuid()}">${tr}</tr>`
                })

              }
              el.innerHTML = tbody
            }
          })
          this.mergeTableCells(nodes, 0);
        }
        // 保存变量值
        const variableContent = {
          columns: tableAttrs,
          titles: tableTitles,
          data: tableDatas
        }
        const formData = new FormData();
        formData.append("docNo", this.$store.state.xmleditor.docInfo.docNo);
        formData.append("id", Number.parseInt(tableId?.variableId));
        formData.append("variableContent", JSON.stringify(variableContent));
        saveVeriableValue(formData);
        // 设置工况总数
        let contentValue = sum || 0;

        this.allVariables = this.$store.state.xmleditor.allVariableContent;
        const meterialCount = this.allVariables.filter(el => {
          return el.variableCode == 'loadCaseStatistics.sum'
        })
        const meterialCountNode = doc.querySelectorAll(`[data-variable-id="${meterialCount[0]?.id}"]`);
        meterialCountNode.forEach(item => {
          item.innerText = contentValue;
        })
        this.dialogVisible = false;
      },
      indexMethod(index) {
        return (
          (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
        );
      },
      async onSearch() {
        try {
          this.loading = true;
          const res = await getLoadCaseStatisticList({
            ...this.queryParams,
            ...this.formInline,
          });
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.$nextTick(() => {
            this.setSelectRow();
          })
        } catch (error) {
          console.log(error);
        } finally {
          this.loading = false;
        }
      },
      handleReset() {
        this.formInline = {
          keyword: "",
          classifyId: null
        };
        this.currentNode = null;
        this.highLight = false;
        this.onSearch();
      },
      handleSearch() {
        this.queryParams.pageNum = 1;
        this.onSearch();
      },
      handleSizeChange(val) {
        if (this.queryParams.pageSize * val > this.total) {
          this.queryParams.pageNum = 1;
        }
        this.onSearch();
      },
      handlepageNumChange() {
        this.onSearch();
        this.isPageChange = true;
      },
      handleSelectionChange(val) {
        this.selectionListAll = val;
      },
      selectionChange(val) {
        // 表格选项发生变化
        this.selectionList = val
        this.$nextTick(() => {
          this.changePageCoreRecordData()
        })
      },
      // 记忆选择核心方法
      changePageCoreRecordData() {
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const that = this
        // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
        if (this.selectionListAll.length <= 0) {
          this.selectionListAll = this.selectionList
          return
        }
        // 总选择里面的key集合
        const selectAllIds = []
        this.selectionListAll.forEach(row => {
          selectAllIds.push(row[idKey])
        })
        const selectIds = []
        // 获取当前页选中的id
        this.selectionList.forEach(row => {
          selectIds.push(row[idKey])
          // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
          if (selectAllIds.indexOf(row[idKey]) < 0) {
            that.selectionListAll.push(row)
          }
        })
        const noSelectIds = []
        // 得到当前页没有选中的id
        this.tableData.forEach(row => {
          if (selectIds.indexOf(row[idKey]) < 0) {
            noSelectIds.push(row[idKey])
          }
        })
        noSelectIds.forEach(id => {
          if (selectAllIds.indexOf(id) >= 0) {
            for (let i = 0; i < that.selectionListAll.length; i++) {
              if (that.selectionListAll[i][idKey] == id) {
                // 如果总选择中有未被选中的，那么就删除这条
                that.selectionListAll.splice(i, 1)
                break
              }
            }
          }
        })
      },
      // 设置选中的方法
      setSelectRow() {
        if (!this.selectionListAll || this.selectionListAll.length <= 0) {
          return
        }
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const selectAllIds = []
        this.selectionListAll.forEach(row => {
          selectAllIds.push(row[idKey])
        })
        this.$refs.tableRef.clearSelection()
        for (var i = 0; i < this.tableData.length; i++) {
          if (selectAllIds.indexOf(this.tableData[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="table"
            this.$refs.tableRef.toggleRowSelection(this.tableData[i], true)
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .home {
    display: flex;

    .left {
      width: 20%;
      margin-top: 60px;

      .customer-menu {
        position: absolute;
        background-color: #fff;
        border: 1px solid #ebebeb;
        border-radius: 3px;
        width: 80px;
        z-index: 1000;
        font-size: 12px;

        ul {
          margin: 0;
          padding: 5px 0;
          list-style: none;
        }

        ul li {
          padding: 3px 15px;
          cursor: pointer;
          display: flex;
          align-items: center;
        }

        ul li:hover {
          background-color: #eee;
        }
      }
    }

    .right {
      width: 80%;
    }
  }
</style>